package cloud

import (
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"reflect"
	"smart_home/api/bots"
	"smart_home/api/bots/depots"
	"smart_home/api/models"
)

type Aligenie struct {
	bots.BotInfo
	Intent *depots.Aligenie // 意图
}

func init() {
	bots.AddBots("aligenie", new(Aligenie))
}

func (c *Aligenie) Init() {
	var (
		uid    string
		refVal reflect.Value
		method reflect.Value
		in     = make([]reflect.Value, 0)
		err    error
	)

	c.Intent = &depots.Aligenie{}
	c.Answer = c.Intent.ToText("我还不懂您说什么")

	if err := json.Unmarshal(c.Body, c.Intent); err != nil {
		logs.Error(err)
		return
	}
	logs.Debug("%+v", c.Intent)
	if len(c.Intent.Token) == 0 {
		//goto NoAuth
		c.Intent.Token = "bhnncjnjij4qts88n3v0"
	}
	uid = bots.GetToken(c.Intent.Token, c.Platform)
	if len(uid) == 0 {
		goto NoAuth
	}

	logs.Debug("uid:", uid)
	if c.User, err = models.GetUserById(uid); err != nil {
		goto NoAuth
	}

	refVal = reflect.ValueOf(c)
	method = refVal.MethodByName(c.Intent.IntentName)
	if method.IsValid() {
		method.Call(in)
	}
	return

NoAuth:
	c.Answer = c.Intent.ToText("请登陆后再操作")
	return
}

// 打开设备
func (c *Aligenie) Open() {
	res := bots.SwitchDevice(c.User.Id, c.Intent.GetSlotInfo("name").StandardValue, true)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.ToText(res.Message)
	}
}

// 关闭设备
func (c *Aligenie) Close() {
	res := bots.SwitchDevice(c.User.Id, c.Intent.GetSlotInfo("name").StandardValue, false)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.ToText(res.Message)
	}
}

// 定时打开
func (c *Aligenie) TimingOpen() {
	tm := c.Intent.GetSlotInfo("time").ParsingTime()
	res := bots.TimingDevice(c.User.Id, c.Intent.GetSlotInfo("name").StandardValue, tm.IDateString, tm.Description, true)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.ToText(res.Message)
	}
}

// 定时关闭
func (c *Aligenie) TimingClose() {
	tm := c.Intent.GetSlotInfo("time").ParsingTime()
	res := bots.TimingDevice(c.User.Id, c.Intent.GetSlotInfo("name").StandardValue, tm.IDateString, tm.Description, false)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.ToText(res.Message)
	}
}
